import React from 'react'
import Util from '../util/index'
import Loading from './Loading'
// import ReactLoading from 'react-loading'
import classnames from 'classnames'
// import Preloader from '../Preloader.js'
import BackRoom from './BackRoom'
import Modal from './Modal'
// import Majiang from './majiang/reactVersion/App.jsx'
import Majiang from './majiang/egretVersion/AppEgret.jsx'
// import Niuniu from './niuniu/Niuniu.jsx'
import Niuniu from './niuniu/egretVersion/AppEgret.jsx'
// import Paodekuai from './paodekuai/PdkApp.jsx'
import Paodekuai from './paodekuai/egretVersion/AppEgret.jsx'
// import Jinhua from './jinhua/JinhuaApp.jsx'
// import Jinhua from './jinhua/egretVersion/AppEgret.jsx'

class Manager extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      loading: true,
      tokenOutDated: false,
      errorTip: '',
      battleData: {
        finishList: [],
        room: {}
      },
      gameInfo: { component: () => <div></div> },
      imageReady: false,
      imageSrc: null,
      forceShowDom: false,
      showModal: false
    }
    this.errorCount = 0
    this.util = new Util()
    window.util = this.util
    this.pre = this.util.getPreUrl()
    this.gameList = [
      { name: '新跑得快', gameId: 16, component: Paodekuai, images: 'imgJson/paodekuai.json', height: 1166, width: 720 },
      { name: '跑得快', gameId: 8, component: Paodekuai, images: 'imgJson/paodekuai.json', height: 1166, width: 720 },
      { name: '红中麻将', gameId: 3, component: Majiang, images: 'imgJson/majiang.json', height: 1166, width: 720 },
      { name: '长沙麻将', gameId: 10, component: Majiang, images: 'imgJson/majiang.json', height: 1166, width: 720 },
      { name: '惠州麻将', gameId: 13, component: Majiang, images: 'imgJson/majiang.json', height: 1166, width: 720 },
      { name: '平江扎鸟', gameId: 11, component: Majiang, images: 'imgJson/majiang.json', height: 1166, width: 720 },
      { name: '欢乐金花', gameId: 4, component: Niuniu, images: 'imgJson/jinhua.json', height: 1166, width: 720 },
      { name: '经典斗牛', gameId: 1, component: Niuniu, images: 'imgJson/niuniu.json', height: 1166, width: 720 },
      { name: '斗公牛', gameId: 2, component: Niuniu, images: 'imgJson/niuniu.json', height: 1166, width: 720 },
      { name: '点子牛', gameId: 5, component: Niuniu, images: 'imgJson/niuniu.json', height: 1166, width: 720 },
      { name: '三公', gameId: 6, component: Niuniu, images: 'imgJson/niuniu.json', height: 1166, width: 720 },
      { name: '平江开船', gameId: 6, component: Niuniu, images: 'imgJson/niuniu.json', height: 1166, width: 720 }
    ]
    this.captured = false
    window.eventDispatcher = new egret.EventDispatcher()
    window.manager = this
    window.labelRenderTime = 1000
    RES.loadConfig('resource/default.res.json', 'resource/')
  }

  get orientation() {
    return document.body.offsetHeight / document.body.offsetWidth <= 1.3 ? 'landscape' : 'portrait'
  }

  componentDidMount() {
    this.loadData()
    // this.listenToRender()
    // this.preloader = new Preloader()
    setTimeout(() => {
      if (!this.state.imageReady) {
        window.location.reload()
      }
    }, 12000)
  }

  // listenToRender() {
  //   document.getElementById('manager').addEventListener('renderComplete', function() {
  //     setTimeout(() => {
  //       this.doCapture()
  //     }, 1000)
  //   }.bind(this))
  // }

  captureComplete(imageSrc) {
    console.log('captureComplete')
    this.setState({ imageReady: true, imageSrc, forceShowDom: false }) // 关闭截图
  }

  // doCapture() {
  //   this.captured = true
  //   console.log('doCapture')
  //   html2canvas(document.querySelector('.result-wrapper'), {scale: 1}).then(canvas => {
  //     this.setState({imageReady: true, imageSrc: canvas.toDataURL('image/png')})
  //   }, err => {
  //     console.log(err)
  //     this.setState({forceShowDom: true, showModal: true})
  //   })
  // }

  loadData() {
    var token = this.util.getQueryString('token')
    var gameNo = this.util.getQueryString('gameNo')
    var areaCode = this.util.getQueryString('areaCode')

    sessionStorage.setItem('token', token)
    sessionStorage.setItem('areaCode', areaCode)
    var url = `${this.pre}/crowd/room/combat/${areaCode}/${gameNo}`
    var opt = { method: 'GET', headers: { Authorization: token } }
    this.setState({ loading: true })
    fetch(url, opt).then(res => res.json()).then(data => {
      console.log('data', data)
      if (data.result) {
        if (data.result === 600) {
          // this.setState({tokenOutDated: true, errorTip: data.message})
          window.location.href = data.data
        } else {
          this.onLoadError()
        }
      } else {
        console.log('loadData suc', data.data)
        const battleData = data.data
        var clubRoom = battleData.clubRoom
        const gameInfo = this.gameList.find(game => game.gameId === battleData.room.gameType)
        document.title = gameInfo.name + '战绩'
        let clickShare = battleData.oauthMode === 'xianliao'
        this.setState({ loading: false, tokenOutDated: false, battleData, gameInfo, clubRoom, clickShare })
        if (battleData.oauthMode === 'xianliao') {
          sessionStorage.setItem('oauthMode', 'xianliao')
        }

        // 2秒还没截图完毕强制显示
        setTimeout(() => {
          if (!this.state.imageReady) {
            this.setState({ forceShowDom: true })
          }
        }, 2000)
      }
    })
  }

  componentDidUpdate(prevProps, prevState) {
    const { imageReady } = this.state
    if (imageReady && !prevState.imageReady) {
      // alert('captured!')
      // this.doCapture()
      document.getElementById('manager').dispatchEvent(new Event('captured'))
      window.postMessage('captured', '*')
    }
  }

  onLoadError() {
    this.errorCount++
    if (this.errorCount <= 3) {
      setTimeout(() => {
        this.loadData()
      }, 500)
    } else {
      // window.location.reload()
    }
  }

  backroom() {
    // const areaCode = this.util.getQueryString('areaCode')
    // const token = this.util.getQueryString('token')
    // window.location.href = `../hall/index.html?areaCode=${areaCode}&token=${token}`
    window.location.href = battleData.backUrl
  }

  caculateScale() {
    const scaleX = document.body.offsetWidth / this.state.gameInfo.width
    const scaleY = document.body.offsetHeight / this.state.gameInfo.height
    return `scale(${scaleX},${scaleY})`
  }

  onClickShare() {
    let img = document.getElementById('finalImage')
    let extId = this.util.getQueryString('gameNo')
    let body = {
      imageContent: img.src,
      width: 720,
      height: 1166,
      extId
    }
    var token = sessionStorage.getItem('token')
    var areaCode = sessionStorage.getItem('areaCode')
    var url = `${this.pre}/gameShare/combat`
    var opt = { method: 'POST', headers: { Authorization: token, AreaCode: areaCode, 'Content-Type': 'application/json;charset=utf-8' }, body: JSON.stringify(body) }
    // this.setState({ loading: true })
    fetch(url, opt).then(res => res.json()).then(data => {
      console.log('data', data)
      alert(data.message);
    })
  }

  render() {
    const { loading, tokenOutDated, battleData, gameInfo, imageReady, imageSrc, forceShowDom, showModal, clickShare } = this.state
    console.log('loading', loading)
    const ShowComponent = gameInfo.component
    const imageCn = classnames({ 'full-height': this.orientation === 'landscape', 'full-bigger': this.orientation === 'portrait' })
    const managerCn = classnames({ full: true, 'text-center': imageReady, 'overflow-hidden': imageReady || forceShowDom })
    const showDom = (!loading && !tokenOutDated && !imageReady) || forceShowDom
    const showImage = imageReady
    const showLoading = (loading || !imageReady) && !forceShowDom
    const isMiniProgram = this.util.getQueryString('miniProgram') === 'true'
    // if (forceShowDom) {
    //   document.getElementById('share').style.transform = this.caculateScale()
    //   if (this.orientation === 'portrait') {
    //     document.getElementById('share').style['-webkit-transform-origin-x'] = 'left'
    //   }
    // }
    const clickShareStyle = this.orientation === 'portrait' ? {
      position: 'absolute',
      right: '9%',
      bottom: '4%',
      width: '32%',
      height: '7%',
      zIndex: '99'
    } : {
      position: 'absolute',
      right: '25%',
      bottom: '4%',
      width: '25%',
      height: '7%',
      zIndex: '99'
    }
    return <div className={managerCn} id="manager">
      {
        showDom ? <div className="full" id="page-show">
          <ShowComponent battleData={battleData} gameInfo={gameInfo}
            backroom={this.backroom.bind(this)} isMiniProgram={isMiniProgram}></ShowComponent>
        </div> : null
      }
      {
        showImage ? <img className={imageCn} id="finalImage" crossorigin="anonymous" src={imageSrc}></img> : null
      }
      {
        showImage && !isMiniProgram ? <BackRoom gameInfo={gameInfo} orientation={this.orientation} backroom={this.backroom.bind(this)}></BackRoom> : null
      }
      {/*  */}
      {
        showLoading ? <div className="loading-page">
          <Loading tokenOutDated={tokenOutDated}></Loading>
        </div> : null
      }
      {/* {
        tokenOutDated ? <div className="loading-page">
          <ReactLoading type="balls" color="#ffc257"
            height="300px" width="300px" delay={0}>
          </ReactLoading>
          <div className="loading-text">
            {errorTip}
          </div>
        </div> : null
      } */}
      {
        forceShowDom && showModal ? <Modal close={() => this.setState({showModal: false})} title={'自动截图失败'} text={'如需分享战绩,请使用手机自带的截屏功能'}></Modal> : null
      }

      {
        clickShare ? <div style={clickShareStyle} onClick={this.onClickShare.bind(this)}></div> : null
      }
    </div>
  }
}

export default Manager